package com.qyhl.webtv.module_broke.scoop.addscoop;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.baidu.mobstat.StatService;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.UpTokenBean;
import com.qyhl.webtv.commonlib.entity.broke.ScoopTopicBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_broke.R;
import com.qyhl.webtv.module_broke.R2;
import com.qyhl.webtv.module_broke.utils.radiobutton.AudioRecorder;
import com.qyhl.webtv.module_broke.utils.radiobutton.MediaManager;
import com.qyhl.webtv.module_broke.utils.radiobutton.RecordButton;
import com.qyhl.webtv.module_broke.utils.radiobutton.ScoopRadioButton;
import com.qyhl.webtv.module_broke.utils.view.RulePopup;
import com.umeng.analytics.MobclickAgent;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2017/12/11.
 * 添加音频爆料
 */

@Route(path = ARouterPathConstant.SCOOP_ADD_RADIO)
public class ScoopAddRadioActivity extends BaseActivity implements ScoopAddContract.ScoopAddView {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.add_cancel)
    TextView addCancel;
    @BindView(R2.id.add_commit)
    TextView addCommit;
    @BindView(R2.id.column_title)
    TextView columnTitle;
    @BindView(R2.id.scoop_flowlayout)
    TagFlowLayout mTagFlowLayout;
    @BindView(R2.id.scoop_title)
    EditText scoopTitle;
    @BindView(R2.id.current_num)
    TextView currentNum;
    @BindView(R2.id.scoop_anonymous)
    ToggleButton scoopAnonymous;
    @BindView(R2.id.scoop_content)
    EditText scoopContent;
    @BindView(R2.id.radio_btn)
    RecordButton radioBtn;
    @BindView(R2.id.radio_player)
    ScoopRadioButton radioPlayer;
    @BindView(R2.id.location)
    TextView mLocation;
    @BindView(R2.id.contact)
    EditText contact;
    @BindView(R2.id.rule)
    TextView rule;
    @BindView(R2.id.layout_one)
    LinearLayout layoutOne;
    @BindView(R2.id.scoop_content_title)
    TextView scoopContentTitle;
    @BindView(R2.id.radioGroup)
    RadioGroup radioGroup;
    private List<ScoopTopicBean> tagList;

    private int isPrivate = 0;
    private String cAnonymous;
    private String cTitle;
    private String cContent;
    private String cAuthor;
    private int cPlateId;
    private String cCreator;
    private String cCreatorAvatar;
    private String cPhone;
    private String cAddress;
    private String mDuration;


    private List<Integer> tagIndex;
    private Iterator<Integer> iterator;
    private Map<String, File> upload;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private String path, address;

    private String[] locationChoose = {"是", "否"};
    private int mIndex = 0;

    private LoadingDialog.Builder builder;
    private boolean addCommitEnalbe = true;

    private ScoopAddPresenter mPresenter;

    private static String curVoicePath;

    private File file;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.black_40per));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

    }

    @Override
    protected int getContentView() {
        return R.layout.broke_activity_scoop_add_radio;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {

    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new ScoopAddPresenter(this);
        tagList = (List<ScoopTopicBean>) getIntent().getExtras().getSerializable("taglist");
        tagList.remove(0);
        initView();

    }

    @Override
    protected void setListener() {
        setListeners();
    }


    /**
     * 初始化
     */
    private void initView() {
        mPresenter.getToken();
        if (CommonUtils.getInstance().getSite() == 174) {
            title.setText("添加");
            columnTitle.setText("类型");
            scoopTitle.setHint("标题");
            scoopContentTitle.setText("内容  (");
            rule.setText("《协议》");
        } else {
            title.setText("添加内容");
            columnTitle.setText("内容类型");
            scoopTitle.setHint("内容标题");
            scoopContentTitle.setText("内容  (");
            rule.setText("《问答协议》");
        }

        //提交等待动画
        builder = new LoadingDialog.Builder(ScoopAddRadioActivity.this);
        builder.setTitle("提交中...");
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);
//        builder.showProgress(true);


        //话题选择
        mTagFlowLayout.setMaxSelectCount(1);//最多选一个标签

        mTagFlowLayout.setAdapter(new TagAdapter<ScoopTopicBean>(tagList) {
            @Override
            public View getView(FlowLayout parent, int position, ScoopTopicBean tag) {
                TextView tv = (TextView) LayoutInflater.from(ScoopAddRadioActivity.this).inflate(R.layout.broke_item_scoop_add_tag,
                        mTagFlowLayout, false);
                tv.setText("#" + tag.getName() + "#");
                return tv;
            }
        });
        //--------------------------------------定位--------------------------------------
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Battery_Saving，低功耗模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);

        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(15000);

        mLocationOption.setInterval(2000);

        try {
            mLocationClient = new AMapLocationClient(getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);

        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

        radioBtn.setAudioRecord(new AudioRecorder());

        radioBtn.setRecordListener(new RecordButton.RecordListener() {
            @Override
            public void recordEnd(String filePath, float time) {
                curVoicePath = filePath;
                radioBtn.setVisibility(View.GONE);
                radioPlayer.setVisibility(View.VISIBLE);
                radioPlayer.setPlayerPath(filePath);
            }
        });


        radioPlayer.setDeleteListener(new ScoopRadioButton.OnDeleteListener() {
            @Override
            public void deleteEvent() {
                reset();
                curVoicePath = null;
            }
        });

    }


    public void reset() {
        if (radioPlayer != null) {
            radioPlayer.release();
        }
        radioPlayer.setVisibility(View.GONE);
        radioBtn.setVisibility(View.VISIBLE);
        if (StringUtils.isNotEmpty(curVoicePath)) {
            File file = new File(curVoicePath);
            if (file != null) {
                file.delete();
            }
        }
    }

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(final AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    address = aMapLocation.getDistrict() + aMapLocation.getStreet() + aMapLocation.getStreetNum() + aMapLocation.getAoiName() + aMapLocation.getBuildingId();
                    mLocation.setText(address);
                } else {
                    Toasty.normal(ScoopAddRadioActivity.this, "定位失败！", Toast.LENGTH_SHORT).show();
                    mLocation.setText("所在地址");
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                }
            }
            mLocationClient.stopLocation();
        }
    };

    /**
     * 监听
     */
    private void setListeners() {
        //是否公开
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.private_button) {
                    isPrivate = 1;
                } else if (checkedId == R.id.public_button) {
                    isPrivate = 0;
                }
            }
        });
        //协议
        rule.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RulePopup rulePopup = new RulePopup(ScoopAddRadioActivity.this);
                rulePopup.setPopupWindowFullScreen(true);
                rulePopup.showPopupWindow();
            }
        });

        //取消
        addCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //提交
        addCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (addCommitEnalbe) {
                    addCommitEnalbe = false;
                    builder.show();

                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                setCommit();
                                judgeCommit();//提交判断
                            } else {
                                builder.dismiss();
                                RouterManager.routerLogin(ScoopAddRadioActivity.this, 0);
                                Toasty.normal(ScoopAddRadioActivity.this, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                                addCommitEnalbe = true;
                            }
                        }

                        @Override
                        public void error(String s) {

                        }
                    });

                }
            }
        });

        //坐标
        mLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MPermissionUtils.requestPermissionsResult(ScoopAddRadioActivity.this, 1, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        AlertDialog.Builder builder = new AlertDialog.Builder(ScoopAddRadioActivity.this);
                        builder.setTitle("是否显示当前所在地理位置？");
                        builder.setSingleChoiceItems(locationChoose, mIndex, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mIndex = which;
                            }
                        });
                        builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if ("是".equalsIgnoreCase(locationChoose[mIndex])) {
                                    mLocationClient.startLocation();
                                } else {
                                    mLocation.setText("所在地址");
                                }
                                dialog.dismiss();
                            }
                        }).show();
                    }

                    @Override
                    public void onPermissionDenied() {
                        MPermissionUtils.showTipsDialog(ScoopAddRadioActivity.this);
                    }
                });
            }
        });

        //内容字数监听
        scoopContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                currentNum.setText(scoopContent.getText().toString().length() + "");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //标题
        scoopTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtils.isEmpty(s.toString())) {
                    setCommit();
                } else {
                    resetCommit();
                }
            }
        });

        builder.getmDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });

    }

    /**
     * 提交判断
     */
    private void judgeCommit() {
        //判断标题
        cTitle = scoopTitle.getText().toString();
        if (StringUtils.isEmpty(cTitle)) {
            Toasty.normal(ScoopAddRadioActivity.this, "标题不能为空！", Toast.LENGTH_SHORT).show();
            resetCommit();
            builder.dismiss();
            return;
        }

        //判断内容
        cContent = scoopContent.getText().toString();
        if (StringUtils.isEmpty(cContent)) {
//            showMessage("描述内容不能为空！");
//            return;
            cContent = "";
        }

        //判断内容类型
        tagIndex = new ArrayList<>();
        iterator = mTagFlowLayout.getSelectedList().iterator();
        while (iterator.hasNext()) {
            tagIndex.add(iterator.next());
        }

        if (tagIndex.size() > 0) {
            cPlateId = tagList.get(tagIndex.get(0)).getId();
        } else {
            Toasty.normal(ScoopAddRadioActivity.this, "请选择类型！", Toast.LENGTH_SHORT).show();
            resetCommit();
            builder.dismiss();
            return;
        }

        mDuration = DateUtils.voiceDuration(radioPlayer.getDuration());

        Log.i("@@@", curVoicePath + "");
        if (StringUtils.isEmpty(curVoicePath)) {
            file = null;
        } else {
            file = new File(curVoicePath);
            if (file.exists() && file.length() == 0) {
                Toasty.normal(ScoopAddRadioActivity.this, "资源出错！").show();
                resetCommit();
                builder.dismiss();
                return;
            }
        }

        //判断联系方式
        cPhone = contact.getText().toString();
        if (StringUtils.isEmpty(cPhone)) {
            cPhone = "";
        }

        //判断地址
        cAddress = mLocation.getText().toString();
        if ("所在地址".equals(cAddress) || StringUtils.isEmpty(cAddress)) {
            cAddress = "";
        }

        //用户信息
        String userName = CommonUtils.getInstance().getUserName();
        String headicon = CommonUtils.getInstance().getUserLogo();
        cCreator = userName;
        cCreatorAvatar = headicon;
        String nickName = CommonUtils.getInstance().getNickName();
        cAuthor = nickName;

        //是否匿名
        if (scoopAnonymous.isChecked()) {
            cAnonymous = "0";
        } else {
            cAnonymous = "1";
        }

        //提交
//        mPresenter.commit(cAnonymous, cTitle, cContent, "2", cAuthor, cPlateId + "", cCreator, cCreatorAvatar, mDuration, cPhone, cAddress, file,isPrivate);
    }

    /**
     * 提交失败
     *
     * @param msg
     */
    @Override
    public void commitError(String msg) {
        builder.dismiss();
        Toasty.normal(ScoopAddRadioActivity.this, msg, Toast.LENGTH_SHORT).show();
        resetCommit();
        addCommitEnalbe = true;
    }

    /**
     * 提交成功
     *
     * @param msg
     */
    @Override
    public void commitSuccess(String msg) {
        builder.dismiss();
        Toasty.normal(ScoopAddRadioActivity.this, msg, Toast.LENGTH_SHORT).show();
        addCommitEnalbe = true;
        finish();
    }

    @Override
    public void cancelCommit() {
        resetCommit();
        addCommitEnalbe = true;
    }

    /**
     * 设置上传进度
     *
     * @param progress
     */
    @Override
    public void setProgress(float progress) {
        int per = (int) (progress * 100);
        if (per % 1 == 0) {
            handler.sendEmptyMessage(per);
        }

    }

    @Override
    public void getTokenSuccess(UpTokenBean data) {

    }


    /**
     * 设置提交按钮
     */
    private void setCommit() {
        addCommit.setEnabled(false);
        addCommit.setTextColor(getResources().getColor(R.color.global_gray_lv2));
        addCommit.setBackgroundResource(R.drawable.scoop_commit_off);
    }

    /**
     * 恢复提交按钮
     */
    private void resetCommit() {
        addCommit.setEnabled(true);
        addCommit.setTextColor(getResources().getColor(R.color.global_base));
        addCommit.setBackgroundResource(R.drawable.scoop_commit_on);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        StatService.onResume(this);
        StatService.onPageStart(this, "添加视频内容");
        //umeng
        MobclickAgent.onPageStart("添加视频内容");
        MobclickAgent.onResume(this);
    }


    @Override
    protected void onPause() {
        super.onPause();
        //baidu
        StatService.onPause(this);
        StatService.onPageEnd(this, "添加视频内容");
        //umeng
        MobclickAgent.onPageEnd("添加视频内容");
        MobclickAgent.onPause(this);
        MediaManager.getIntance().release();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        reset();
    }




    Handler handler = new MyHandler(this);


    private static class MyHandler extends Handler {
        private final WeakReference<ScoopAddRadioActivity> mActivity;

        public MyHandler(ScoopAddRadioActivity activity) {
            mActivity = new WeakReference<ScoopAddRadioActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            ScoopAddRadioActivity scoopAdd = mActivity.get();
            scoopAdd.builder.setProgress(msg.what);
        }

    }


}
